import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PageService } from 'app/utils/page.service'
import { CommonService } from 'app/utils/common.service'
import { ReportManageService } from 'app/services/report/report-manage.service'
@Component({
  selector: 'app-report-detail',
  templateUrl: './report-detail.component.html',
  styleUrls: ['./report-detail.component.less']
})
export class ReportDetailComponent implements OnInit {
  private reportId
  private reportObject
  private reportForm: FormGroup
  private taskForm: FormGroup
  private authForm: FormGroup
  private dateOptions: Array<Object> = []
  private teamOptions: Array<Object> = []
  private completeOptions: Array<Object> = [{
    label: '未完成',
    value: 0,
  }, {
    label: '25%',
    value: 0.25,
  }, {
    label: '50%',
    value: 0.5,
  }, {
    label: '75%',
    value: 0.75,
  }, {
    label: '已完成',
    value: 1,
  }]
  private projectOptions: Array<Object> = []
  private userOptions: Array<Object> = []
  private completeDataSet: Array<Object> = [] // 完成任务列表
  private planDataSet: Array<Object> = [] // 计划任务列表
  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private commonService: CommonService,
    private modalService: NzModalService,
    private messageService: NzMessageService,
    private reportManageService: ReportManageService
  ) {
    this.reportId = this.route.snapshot.params.id;

    this.reportForm = this.fb.group({
      date: [],  // 周报日期
      team: [],   // 周报团队
    })

    this.taskForm = this.fb.group({
      content: [],  // 任务内容
      project: [],  // 任务项目
      user: [], // 任务成员
      date: [], // 任务目标日期
    })

    this.authForm = this.fb.group({
      complete: [],  // 完成程度
      remark: [] // 备注
    })
  }

  /**
   * 初始化
   */
  async ngOnInit() {
    this.generateDateOptions()  // 生成周报待选日期
    await this.getUserTeams() // 生成周报用户团队

    // 获取周报实体
    if (this.reportId) {
      this.reportManageService.getReport(this.reportId).then(report => {
        this.reportObject = report
        Promise.all([
          this.getTeamProjects(),
          this.getTeamUsers()
        ]).then(() => {
          let date = this.dateOptions.find((x: any) => x.start === this.reportObject.get('start') && x.end === this.reportObject.get('end'))
          let team = this.teamOptions.find((x: any) => x.object.id === this.reportObject.get('team').id)

          if (!date) {
            date = {
              label:`${this.commonService.dateFormat(this.reportObject.get('start'), 'yyyy-MM-dd')} - ${this.commonService.dateFormat(this.reportObject.get('end'), 'yyyy-MM-dd')} `,
              start: this.reportObject.get('start'),
              end: this.reportObject.get('end')
            }
            this.dateOptions.push(date)
          }

          this.reportForm.setValue({
            date: date,  // 周报日期
            team: team,   // 周报团队
          })
        }).then(() => {
          this.getCompleteTasks()
          this.getPlanTasks()
        })
      })
    }
  }

  /**
   * 获取团队成员
   */
  getTeamUsers() {
    let team = this.reportObject.get('team')
    return this.reportManageService.getTeamUsers(team)
      .then((data: Array<any>) => data.map(x => ({
        realname: x.get('realname'),
        object: x
      })))
      .then(data => {
        this.userOptions = data
      })
  }


  /**
   * 获取团队项目
   */
  getTeamProjects() {
    let team = this.reportObject.get('team')
    return this.reportManageService.getTeamProjects(team)
      .then((data: Array<any>) => data.map(x => ({
        name: x.get('name'),
        object: x
      })))
      .then(data => {
        this.projectOptions = data
      })
  }

  /**
   * 保存周报信息
   */
  saveReport() {
    let isUpdate = !this.reportObject
    this.reportManageService.saveReport({
      start: this.reportForm.value.date.start,
      end: this.reportForm.value.date.end,
      team: this.reportForm.value.team.object,
    }).then(data => {
      if (isUpdate) {
        return
      }
      this.reportId = data.id
      this.reportObject = data
      this.getTeamProjects()
      this.getTeamUsers()
      // 生成完成周报信息
      this.reportManageService.generateCompleteTasks(this.reportObject).then((data: Array<any>) => {
        this.getCompleteTasks()
      })
    }, error => {
      this.messageService.create('error', error)
    })
  }

  /**
   * 生成周报待选择日期
   */
  generateDateOptions() {
    let now = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())
    const dayTime = 24 * 60 * 60 * 1000
    let monday = +now - (now.getDay() - 1) * dayTime
    let firday = monday + 4 * dayTime

    let weeks = [-1, 0, 1].map(x => ({
      start: monday + (x * 7 * dayTime),
      end: firday + (x * 7 * dayTime)
    }))

    this.dateOptions = weeks.map(x => ({
      label: `${this.commonService.dateFormat(new Date(x.start), 'yyyy-MM-dd')} - ${this.commonService.dateFormat(new Date(x.end), 'yyyy-MM-dd')} `,
      start: x.start,
      end: x.end
    }))
  }

  /**
   * 获取当前用户所在团队
   */
  async getUserTeams() {
    return this.reportManageService.getUserTeams()
      .then((data: any) => data.map(x => ({
        name: x.get('name'),
        admin: x.get('admin'),
        object: x
      })))
      .then(data => {
        this.teamOptions = data
      })
  }

  showAuthDialog(content, data) {
    let task = data.get('task')
    // 重置任务表单
    this.authForm.setValue({
      complete: data.get('complete') || 0,
      remark: data.get('remark') || ''
    })

    this.modalService.open({
      title: '任务审核',
      content: content,
      maskClosable: false,
      onOk: () => {
        this.saveCompleteTask({
          id: data.id,
          task: task,
          complete: this.authForm.value.complete,
          remark: this.authForm.value.remark
        })
      }
    });
  }

  showTaskDialog(content, type) {
    // 重置任务表单
    this.taskForm.reset()
    this.modalService.open({
      title: '添加任务',
      content: content,
      maskClosable: false,
      onOk: () => {
        this.saveTask(type)
      }
    });
  }

  saveCompleteTask({ task, complete, remark, id }: { task, complete?, remark?, id?}) {
    this.reportManageService.saveCompleteTask({
      id: id,
      report: this.reportObject,
      task: task,
      complete: complete,
      remark: remark
    })
      .then(data => {
        let project = task.get('project')
        let user = task.get('user')
        if (id) {
          this.getCompleteTasks()
        } else {
          this.completeDataSet.push({
            project: project.get('name'),
            user: user.get('realname'),
            content: task.get('content'),
            complete: data.get('complete'),
            remark: data.get('remark'),
            object: data
          })
        }
      })
  }

  getCompleteTasks() {
    this.reportManageService.getCompleteTasks(this.reportObject)
      .then((data: Array<any>) => data.map(x => {
        let task = x.get('task')
        let project = task.get('project')
        let user = task.get('user')

        return {
          project: project.get('name'),
          user: user.get('realname'),
          content: task.get('content'),
          complete: x.get('complete'),
          remark: x.get('remark'),
          object: x
        }
      }))
      .then((data: Array<any>) => data.map(x => {
        console.log(data)
        switch (x.complete) {
          case 0:
            x.complete = '未完成'
            break;
          case 1:
            x.complete = '已完成'
            break;
          case undefined:
            x.complete = '待审核'
            break;
          default:
            x.complete = x.complete * 100 + "%"
            break;
        }
        return x
      }))
      .then(data => {
        this.completeDataSet = Array.from(data)
      })
  }

  getPlanTasks() {
    this.reportManageService.getPlanTasks(this.reportObject)
      .then((data: Array<any>) => data.map(x => {
        let task = x.get('task')
        let project = task.get('project')
        let user = task.get('user')

        return {
          project: project.get('name'),
          user: user.get('realname'),
          content: task.get('content'),
          object: x
        }
      }))
      .then(data => {
        this.planDataSet = Array.from(data)
      })
  }

  savePlanTask(task) {
    this.reportManageService.savePlanTask({
      report: this.reportObject,
      task: task
    })
      .then(data => {
        let project = task.get('project')
        let user = task.get('user')

        this.planDataSet.push({
          project: project.get('name'),
          user: user.get('realname'),
          content: task.get('content'),
          object: data
        })
      })
  }

  saveTask(type) {
    this.reportManageService.saveTask({
      team: this.reportObject.get('team'),
      project: this.taskForm.value.project,
      user: this.taskForm.value.user,
      date: this.taskForm.value.date,
      content: this.taskForm.value.content,
    }).then(task => {
      switch (type) {
        case 'plan': {
          this.savePlanTask(task)
          break;
        }
        case 'complete': {
          this.saveCompleteTask({ task })
          break;
        }
      }
    })
  }
}
